import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'community_page_controller.dart';
import '../../../function/utils/my_common.dart';
import '../../../function/model/post_model.dart';
import '../../../function/state/post_state.dart';
import '../../../function/state/like_state.dart';
import '../../../routes/app_routes.dart';

/// 社区页面组件
/// 使用非常规命名避免标准模式
class CommunityPage extends GetView<CommunityPageController> {
  const CommunityPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CommunityPageController>(
      init: CommunityPageController(),
      builder: (controller) {
        return Scaffold(
          floatingActionButton: GestureDetector(
            onTap: controller.onPublishButtonTap,
            child: Padding(
              padding: EdgeInsets.only(bottom: 100.h, right: 10.w),
              child: Image.asset(
                'assets/images/release_button.png',
                width: 52.w,
                height: 52.w,
              ),
            ),
          ),
          floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/communal_bg.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    // 随机分类图片
                    _buildRandomCategoryImage(controller),
                    SizedBox(height: 20.h),

                    // 两个按钮
                    _buildActionButtons(),
                    SizedBox(height: 20.h),

                    // Find 标题
                    _buildFindTitle(),
                    SizedBox(height: 16.h),

                    // 帖子列表
                    _buildPostsList(controller),
                    SizedBox(height: 120.h),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建随机分类图片
  Widget _buildRandomCategoryImage(CommunityPageController controller) {
    final category = controller.randomCategory;
    return Container(
      width: double.infinity,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Activity Challenge 标题
          Padding(
            padding: EdgeInsets.only(left: 4.w, bottom: 8.h),
            child: Text(
              'Activity Challenge',
              style: TextStyle(
                fontSize: 24.sp,
                color: MyCommonUtils.white,
                fontFamily:
                    GoogleFonts.berkshireSwash(
                      fontWeight: FontWeight.w400,
                    ).fontFamily,
              ),
            ),
          ),
          // 分类图片
          GestureDetector(
            onTap: () {
              // 导航到植物种植活动挑战页面
              Get.toNamed(
                '/plant_challenge',
                arguments: {'category': category},
              );
            },
            child: Container(
              width: double.infinity,
              height: 152.h,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(category.imagePath),
                  fit: BoxFit.fill,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建操作按钮
  Widget _buildActionButtons() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children: [
          Expanded(
            child: _buildActionButton(
              'assets/images/ai_button.png',
              'AI Assistant',
              () {
                Get.toNamed(AppRoutes.aiChat);
              },
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: _buildActionButton(
              'assets/images/group_button.png',
              'Group Chat',
              () {
                Get.toNamed(AppRoutes.chatGroupList);
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建单个操作按钮
  Widget _buildActionButton(
    String imagePath,
    String label,
    VoidCallback onTap,
  ) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          AspectRatio(
            aspectRatio: 171 / 205,
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12.r),
                image: DecorationImage(
                  image: AssetImage(imagePath),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建Find标题
  Widget _buildFindTitle() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Align(
        alignment: Alignment.centerLeft,
        child: Text(
          'Find',
          style: TextStyle(
            fontSize: 24.sp,
            color: MyCommonUtils.white,
            fontFamily:
                GoogleFonts.berkshireSwash(
                  fontWeight: FontWeight.w400,
                ).fontFamily,
          ),
        ),
      ),
    );
  }

  /// 构建帖子列表
  Widget _buildPostsList(CommunityPageController controller) {
    return GetX<PostState>(
      builder: (postState) {
        final posts = postState.allPosts;
        return Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: MasonryGridView.count(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            crossAxisCount: 2,
            mainAxisSpacing: 12.h,
            crossAxisSpacing: 12.w,
            itemCount: posts.length,
            itemBuilder: (context, index) {
              final post = posts[index];
              return _buildAnimatedPostCard(post, controller, index);
            },
          ),
        );
      },
    );
  }

  /// 构建带动画效果的帖子卡片
  Widget _buildAnimatedPostCard(
    PostModel post,
    CommunityPageController controller,
    int index,
  ) {
    return TweenAnimationBuilder<double>(
      duration: Duration(milliseconds: 300 + (index * 100)),
      tween: Tween(begin: 0.0, end: 1.0),
      builder: (context, value, child) {
        return Transform.translate(
          offset: Offset(0, 50 * (1 - value)),
          child: Opacity(
            opacity: value,
            child: _buildPostCard(post, controller),
          ),
        );
      },
    );
  }

  /// 构建帖子卡片
  Widget _buildPostCard(PostModel post, CommunityPageController controller) {
    return GestureDetector(
      onTap: () {
        // 导航到帖子详情页
        Get.toNamed('/post-detail', arguments: post);
      },
      child: Container(
        decoration: BoxDecoration(
          color: MyCommonUtils.white,
          borderRadius: BorderRadius.circular(12.r),
        ),
        padding: EdgeInsets.only(bottom: 12.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 帖子图片 - 瀑布流中高度可变
            _buildPostImage(post),

            // 帖子标题
            Padding(
              padding: EdgeInsets.all(8.w),
              child: Text(
                post.title,
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w700,
                  color: MyCommonUtils.black,
                  height: 1.2,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),

            // 用户信息和点赞
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 8.w),
              child: Row(
                children: [
                  // 用户头像和用户名
                  Expanded(
                    child: Row(
                      children: [
                        CircleAvatar(
                          radius: 12.w, // 24.w / 2
                          backgroundImage: AssetImage(
                            controller.getUserAvatar(post.userId),
                          ),
                        ),
                        SizedBox(width: 4.w),
                        Expanded(
                          child: Text(
                            controller.getUserName(post.userId),
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: MyCommonUtils.grey,
                              fontWeight: FontWeight.w700,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ),
                  ),

                  // 点赞按钮和数量
                  GetX<LikeState>(
                    builder: (likeState) {
                      final isLiked = controller.isPostLiked(post.id);
                      final likes = controller.getPostLikes(post.id);
                      return Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            isLiked ? Icons.favorite : Icons.favorite_border,
                            size: 22.w,
                            color:
                                isLiked
                                    ? MyCommonUtils.pink
                                    : MyCommonUtils.grey,
                          ).onTap(() => controller.togglePostLike(post.id)),
                          SizedBox(width: 2.w),
                          Text(
                            likes.toString(),
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: MyCommonUtils.grey,
                            ),
                          ),
                        ],
                      );
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建帖子图片
  Widget _buildPostImage(PostModel post) {
    // 为瀑布流生成随机高度，让布局更有趣
    final randomHeight = _getRandomImageHeight(post.id);

    return Hero(
      tag: 'post_image_${post.id}',
      child: Container(
        width: double.infinity,
        height: randomHeight,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(12.r),
            topRight: Radius.circular(12.r),
          ),
          image: DecorationImage(
            image: AssetImage(
              post.resourceType == ResourceType.video
                  ? (post.coverImagePath ?? post.resourcePath)
                  : post.resourcePath,
            ),
            fit: BoxFit.cover,
          ),
        ),
        child:
            post.resourceType == ResourceType.video
                ? Center(
                  child: Container(
                    width: 32.w,
                    height: 32.w,
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.6),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      Icons.play_arrow,
                      color: MyCommonUtils.white,
                      size: 20.sp,
                    ),
                  ),
                )
                : null,
      ),
    );
  }

  /// 根据帖子ID生成随机图片高度，确保瀑布流效果
  double _getRandomImageHeight(String postId) {
    // 使用帖子ID的哈希值来生成一致的随机高度
    final hash = postId.hashCode;
    final heights = [120.h, 150.h, 180.h, 200.h, 220.h, 250.h];
    return heights[hash.abs() % heights.length];
  }
}
